package cn.zhf.shop.utils;

import cn.hutool.crypto.asymmetric.RSA;
import cn.zhf.shop.entity.AdminUser;

import cn.zhf.shop.entity.TokenInfo;

import cn.zhf.shop.expection.InvalidTokenException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static RSA rsa=new RSA(RSAUtils.getKeyFromFile("key.pri"),RSAUtils.getKeyFromFile("key.pub"));


    public static String createJwtToken(AdminUser u)
    {

        Map claims= new HashMap<>();
        claims.put("userName",u.getUserName());
        claims.put("org",u.getOrganizationid());

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(new Date().getTime()+2*60*60*1000))
                .setSubject(u.getUserName())
                .signWith(rsa.getPrivateKey())
                .compact();
    }

    public static Claims resolveToken(String token)throws Exception {
        Jws<Claims> jws;
            jws = Jwts.parserBuilder()  // (1)
                    .setSigningKey(rsa.getPublicKey())         // (2)
                    .build()                    // (3)
                    .parseClaimsJws(token); // (4)
                    return jws.getBody();
            // we can safely trust the JWT
    }

    public static TokenInfo getTokenInfo(String token){
        try {
            Claims claims = resolveToken(token);
            TokenInfo tokenInfo=new TokenInfo();
                tokenInfo.setUserName((String)claims.get("userName"));
                tokenInfo.setOrg((String)claims.get("org"));

            return tokenInfo;
        } catch (Exception e) {
            throw new InvalidTokenException();
        }

    }
}

